package com.cictec.middleware.gps.service;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cictec.middleware.commons.cache.ecache.EHCacheUtils;
import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.core.entity.BusDriverSignIn;
import com.cictec.middleware.gps.service.feign.MiddlewareDcFeignClient;

/**
 * 司机相关信息服务
 * @author ql
 *
 */
@Service
public class BusDriverService {

	private static Logger logger = LoggerFactory.getLogger(BusDriverService.class);


	@Autowired
	private MiddlewareDcFeignClient middlewareDcFeignClient;
	
	/**  司机签到信息缓存 */
	private static String DRIVER_SIGN = "bus-driver-sign";
	
	/**
	 * 【缓存】刷新司机签到信息,加载指定日期及前一天的刷卡信息
	 * @param busUuid
	 * @param date yyyy-mm-dd
	 */
	public void refreshDriverSignIn(String busUuid, String date){
		
		List<BusDriverSignIn> list = middlewareDcFeignClient.selectSignByBusUuid(busUuid, date);
		if(list != null){
			EHCacheUtils.setValue(DRIVER_SIGN, busUuid, list);
		}
	}
	
	/**
	 * 【缓存】根据车辆日期，获取司机签到信息
	 * @param busUuid
	 * @param date
	 * @return
	 */
	public List<BusDriverSignIn> getSignByBusUuid(String busUuid, String date){
		
		logger.debug("加载司机签到缓存 {}  busUuid:{}", date, busUuid);
		
		List<BusDriverSignIn> list = EHCacheUtils.getValue(DRIVER_SIGN, busUuid);
		
		if(list != null){
			return list;
		}
		list = middlewareDcFeignClient.selectSignByBusUuid(busUuid, date);
		
		EHCacheUtils.setValue(DRIVER_SIGN, busUuid, list);
		
		return list;
	}
	
	/**
	 * 【缓存】【司机签到】根据车辆、时间，获取最近一次司机签到信息
	 * @param busUuid
	 * @param currentTime	当前时间
	 * @return
	 */
	public BusDriverSignIn getSignDriver(String busUuid, Date currentTime) {
		
		List<BusDriverSignIn> list = getSignByBusUuid(busUuid, DateUtils.formatDate(currentTime));
		
		BusDriverSignIn driverSignin = null;
		if(list != null && list.size() > 0){
			
//			DriverSignIn driverSignin = null;
			for (BusDriverSignIn signIn : list) {
				if(!PMSUtils.isEmpty(signIn.getDrvSignTime()) && signIn.getDrvSignTime().getTime() < currentTime.getTime()){
					driverSignin = signIn;
				}
			}
		}
		
		return driverSignin;
	}
	
	
}
